package com.mc.fastkit.view.shape

import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.toColorInt
import com.mc.fastkit.R
import com.mc.fastkit.view.StateType
import com.mc.fastkit.view.text.IStateText
import com.mc.fastkit.view.text.StateTextDelegate


/**
 * ShapedTextView
 * @author: MasterChan
 * @date: 2023-03-11 21:36
 */
open class ShapedTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr),
    IShapedView by ShapedViewDelegate(context, attrs),
    IStateText by StateTextDelegate(context, attrs) {

    private var colorStr: String? = null
    private var positionStr: String? = null
    private var gradientOrientation: Int = 0

    init {
        this.init()
        initTextGradient(attrs)
    }

    protected open fun init() {
        into(this)
        setStateTextTarget(this).setStateTextStateType(stateType)
    }

    override fun setStateType(stateType: StateType): IShapedView {
        setStateTextStateType(stateType)
        return super.setStateType(stateType)
    }

    protected fun initTextGradient(attrs: AttributeSet?) {
        context.withStyledAttributes(attrs, R.styleable.ShapedTextView) {
            colorStr = getString(R.styleable.ShapedTextView_mc_textGradientColor)
            positionStr = getString(R.styleable.ShapedTextView_mc_textGradientPosition)
            gradientOrientation = getInteger(
                R.styleable.ShapedTextView_mc_textGradientOrientation, 0
            )
        }
    }

    private fun setGradient() {
        val colors = colorStr!!.split(",").map { it.toColorInt() }.toIntArray()
        val position = positionStr?.split(",")?.map { it.toFloat() }?.toFloatArray()
        val shader = if (gradientOrientation == 0) {
            LinearGradient(0f, 0f, width.toFloat(), 0f, colors, position, Shader.TileMode.CLAMP)
        } else {
            LinearGradient(0f, 0f, 0f, height.toFloat(), colors, position, Shader.TileMode.CLAMP)
        }
        paint.shader = shader
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (!colorStr.isNullOrEmpty()) {
            setGradient()
        }
    }
}